<template>
  <div class="smartlock-timer-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h2>智能锁定时任务管理</h2>
      </div>
      <div class="header-right">
        <el-button 
          type="primary" 
          @click="refreshData" 
          :loading="loading"
          icon="el-icon-refresh"
          size="medium"
        >
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选栏 -->
    <el-form :inline="true" @submit.native.prevent class="search-form">
      <el-form-item>
        <el-input
          v-model="searchKeyword"
          @keyup.native.enter="searchTasks"
          placeholder="请输入任务ID、设备ID或任务详情"
          style="width: 250px; margin-right: 15px"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="statusFilter"
          placeholder="任务状态"
          style="width: 150px; margin-right: 15px"
          clearable
        >
          <el-option label="待执行" value="0"></el-option>
          <el-option label="执行中" value="1"></el-option>
          <el-option label="已完成" value="2"></el-option>
          <el-option label="已取消" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px; margin-right: 15px"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchTasks">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="exportTasks">导出记录</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 批量操作工具栏 -->
    <div class="batch-operation-toolbar" v-show="selectedTasks.length > 0">
      <div class="batch-info">
        <span>已选择 <strong>{{ selectedTasks.length }}</strong> 个任务</span>
      </div>
      <div class="batch-actions">
        <el-button 
          type="danger" 
          size="small" 
          @click="batchCancelTasks"
          :loading="batchCancelling"
        >
          批量取消任务
        </el-button>
        <el-button 
          type="success" 
          size="small" 
          @click="batchExportTasks"
        >
          导出选中项
        </el-button>
        <el-button 
          type="info" 
          size="small" 
          @click="clearSelection"
        >
          清空选择
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="taskData"
      border
      stripe
      style="width: 100%"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      ref="taskTable"
    >
      <el-table-column 
        type="selection" 
        width="55" 
        align="center"
        :selectable="checkSelectable"
      >
      </el-table-column>
      
      <el-table-column type="index" label="序号" width="60" align="center">
      </el-table-column>
      
      <el-table-column prop="taskId" label="任务ID" width="80" align="center">
      </el-table-column>
      
      <el-table-column prop="lockId" label="设备ID" width="80" align="center">
      </el-table-column>
      
      <el-table-column prop="taskDetails" label="任务详情" align="center" min-width="200" show-overflow-tooltip>
      </el-table-column>
      
      <el-table-column label="执行时间" width="120" align="center">
        <template slot-scope="scope">
          {{ formatTime(scope.row.hour, scope.row.minute) }}
        </template>
      </el-table-column>
      
      <el-table-column label="重复周期" width="200" align="center">
        <template slot-scope="scope">
          <span v-for="day in formatDays(scope.row.countDay)" :key="day" style="margin-right: 5px;">
            <el-tag size="mini" type="success">{{ day }}</el-tag>
          </span>
        </template>
      </el-table-column>
      
      <el-table-column prop="taskStatus" label="任务状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag
            :type="getTaskStatusType(scope.row.taskStatus)"
            size="small"
          >
            {{ getTaskStatus(scope.row.taskStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      
       <el-table-column label="循环类型" width="100" align="center">
         <template slot-scope="scope">
           <el-tag
             type="primary"
             size="small"
           >
             循环
           </el-tag>
           <div v-if="scope.row.loopCount > 0" style="font-size: 11px; color: #666; margin-top: 2px;">
             {{ scope.row.loopCount }}次
           </div>
         </template>
       </el-table-column>
      
      <el-table-column prop="createdTime" label="创建时间" align="center" width="160">
        <template slot-scope="scope">
          {{ formatDate(scope.row.createdTime) }}
        </template>
      </el-table-column>
      
      <el-table-column prop="remarks" label="通道号" align="center" show-overflow-tooltip>
      </el-table-column>
      
      <el-table-column label="操作" align="center" width="220">
        <template slot-scope="scope">
          <div style="display: flex; gap: 6px; justify-content: center; align-items: center; flex-wrap: wrap;">
            <el-button
              type="text"
              size="small"
              @click="viewDetails(scope.row)"
            >
              查看详情
            </el-button>
            
            <!-- 运行中的任务显示取消按钮 -->
            <el-button
              v-if="scope.row.taskStatus === 1"
              type="text"
              size="small"
              @click="cancelTask(scope.row)"
              :loading="scope.row.cancelling"
              style="color: #f56c6c;"
            >
              取消任务
            </el-button>
            
            <!-- 待执行或已取消的任务显示启动按钮 -->
            <el-button
              v-if="scope.row.taskStatus === 0 || scope.row.taskStatus === 3"
              type="text"
              size="small"
              @click="startTask(scope.row)"
              style="color: #67c23a;"
            >
              启动任务
            </el-button>
            
            <!-- 所有任务都显示编辑按钮 -->
            <el-button
              type="text"
              size="small"
              @click="editTask(scope.row)"
              style="color: #409eff;"
            >
              编辑
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        background
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      title="定时任务详情"
      :visible.sync="dialogVisible"
      width="700px"
      :modal="false"
    >
      <div v-if="selectedTask">
        <!-- 任务基本信息 -->
        <h4>任务基本信息</h4>
        <el-descriptions :column="2" border style="margin-bottom: 20px;">
          <el-descriptions-item label="任务ID">{{ selectedTask.taskId }}</el-descriptions-item>
          <el-descriptions-item label="设备ID">{{ selectedTask.lockId }}</el-descriptions-item>
          <el-descriptions-item label="任务详情">{{ selectedTask.taskDetails || '定时开锁任务' }}</el-descriptions-item>
          <el-descriptions-item label="任务状态">
            <el-tag :type="getTaskStatusType(selectedTask.taskStatus)" size="small">
              {{ getTaskStatus(selectedTask.taskStatus) }}
            </el-tag>
          </el-descriptions-item>
           <el-descriptions-item label="循环类型">
             <el-tag type="primary" size="small">
               循环执行
             </el-tag>
           </el-descriptions-item>
          <el-descriptions-item label="循环次数">{{ selectedTask.loopCount || '无限制' }}</el-descriptions-item>
          <el-descriptions-item label="通道号">{{ selectedTask.remarks || '无' }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 定时配置信息 -->
        <h4>定时配置信息</h4>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="执行时间">{{ formatTime(selectedTask.hour, selectedTask.minute) }}</el-descriptions-item>
          <el-descriptions-item label="重复周期">
            <span v-for="day in formatDays(selectedTask.countDay)" :key="day" style="margin-right: 5px;">
              <el-tag size="mini" type="success">{{ day }}</el-tag>
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(selectedTask.createdTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDate(selectedTask.updatedTime) }}</el-descriptions-item>
          <el-descriptions-item label="操作类型">定时开锁</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ selectedTask.userId || '系统' }}</el-descriptions-item>
        </el-descriptions>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 任务编辑对话框 -->
    <el-dialog
      :title="editDialogTitle"
      :visible.sync="editDialogVisible"
      width="700px"
      :modal="false"
      @close="resetEditForm"
    >
      <el-form 
        :model="editForm" 
        :rules="editRules" 
        ref="editForm" 
        label-width="100px"
        style="padding: 0 20px;"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h4>基本信息</h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="任务ID" prop="taskId">
                <el-input v-model="editForm.taskId" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="设备ID" prop="lockId">
                <el-input v-model="editForm.lockId" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="任务详情" prop="taskDetails">
            <el-input 
              v-model="editForm.taskDetails" 
              placeholder="请输入任务详情说明"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
          
          <el-form-item label="通道号" prop="remarks">
            <el-input 
              v-model="editForm.remarks" 
              type="textarea"
              :rows="3"
              placeholder="通道号"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 定时配置 -->
        <div class="form-section">
          <h4>定时配置</h4>
          <el-form-item label="执行时间" prop="executeTime">
            <el-time-picker
              v-model="editForm.executeTime"
              format="HH:mm"
              value-format="HH:mm"
              placeholder="选择执行时间"
              style="width: 300px;"
            />
          </el-form-item>
          
          <el-form-item label="重复周期" prop="countDay">
            <el-checkbox-group v-model="editForm.countDayArray">
              <el-checkbox :label="0">周一</el-checkbox>
              <el-checkbox :label="1">周二</el-checkbox>
              <el-checkbox :label="2">周三</el-checkbox>
              <el-checkbox :label="3">周四</el-checkbox>
              <el-checkbox :label="4">周五</el-checkbox>
              <el-checkbox :label="5">周六</el-checkbox>
              <el-checkbox :label="6">周日</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          
          <el-form-item label="循环次数" prop="loopCount">
            <el-input-number
              v-model="editForm.loopCount"
              :min="0"
              :max="999"
              placeholder="-2表示无限循环，0代表只执行一次"
              style="width: 200px;"
            />
            <span style="margin-left: 10px; color: #999; font-size: 12px;">-2表示无限循环，0代表只执行一次</span>
          </el-form-item>
        </div>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleEditConfirm"
          :loading="editSubmitting"
        >
          {{ isStartMode ? '确定并启动' : '确定' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 接口路径常量定义
const TIMER_API = {
  GET_TIMER_LIST: '/api/smart/lock/getTimer',
  GET_TIMER_BY_TIME: '/api/smart/lock/getTimerByTime',
  GET_TIMER_BY_ID: '/api/smart/lock/getTimerById',
  UPDATE_TIMER_STATUS: '/api/smart/lock/updateTimerStatus',
  UPDATE_TIMER: '/api/smart/lock/updateTimer',
  CANCEL_TIMER: '/api/smart/lock/cancelWeeklyTimer'
};

export default {
  name: 'SmartLockTimer',
  
  data() {
    return {
      // 搜索参数
      searchKeyword: '',
      statusFilter: '',
      dateRange: null,
      
      // 表格数据
      taskData: [],
      allTasks: [],
      loading: false,
      
      // 分页参数
      currentPage: 1,
      pageSize: 20,
      total: 0,
      
      // 对话框相关
      dialogVisible: false,
      selectedTask: null,
      
      // 批量操作相关
      selectedTasks: [],
      batchCancelling: false,
      
      // 编辑对话框相关
      editDialogVisible: false,
      editDialogTitle: '',
      isStartMode: false, // 是否是启动模式
      editSubmitting: false,
      editForm: {
        taskId: '',
        lockId: '',
        taskDetails: '',
        remarks: '',
        executeTime: '',
        countDayArray: [],
        loopCount: 0,
        hour: 0,
        minute: 0
      },
      editRules: {
        taskDetails: [
          { required: true, message: '请输入任务详情', trigger: 'blur' },
          { min: 1, max: 200, message: '任务详情长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        executeTime: [
          { required: true, message: '请选择执行时间', trigger: 'change' }
        ],
        countDay: [
          { 
            validator: (rule, value, callback) => {
              if (this.editForm.countDayArray.length === 0) {
                callback(new Error('请至少选择一个重复周期'));
              } else {
                callback();
              }
            }, 
            trigger: 'change' 
          }
        ]
      }
    }
  },
  
  
  mounted() {
    this.loadTaskData();
  },
  
  methods: {
    // 加载定时任务数据
    loadTaskData() {
      this.loading = true;
      
      let apiCall = this.$get(TIMER_API.GET_TIMER_LIST);
      
      // 如果有时间范围筛选
      if (this.dateRange && this.dateRange.length === 2) {
        const startTime = this.dateRange[0] + 'T00:00:00';
        const endTime = this.dateRange[1] + 'T23:59:59';
        apiCall = this.$get(TIMER_API.GET_TIMER_BY_TIME, {
          startTime,
          endTime
        });
      }
      
      apiCall.then(res => {
        if (res && res.code === 200) {
          let tasks = res.data || [];
          
          // 前端进行搜索过滤
          if (this.searchKeyword) {
            const keyword = this.searchKeyword.toLowerCase();
            tasks = tasks.filter(task => {
              const taskId = task.taskId ? task.taskId.toString() : '';
              const lockId = task.lockId ? task.lockId.toString() : '';
              const taskDetails = task.taskDetails ? task.taskDetails.toLowerCase() : '';
              const remarks = task.remarks ? task.remarks.toLowerCase() : '';
              return taskId.includes(keyword) || lockId.includes(keyword) || 
                     taskDetails.includes(keyword) || remarks.includes(keyword);
            });
          }
          
          // 前端进行状态过滤
          if (this.statusFilter !== '' && this.statusFilter !== null) {
            const filterValue = parseInt(this.statusFilter);
            tasks = tasks.filter(task => task.taskStatus === filterValue);
          }
          
          this.allTasks = tasks.map(task => ({
            ...task,
            cancelling: false
          }));
          this.total = this.allTasks.length;
          
          // 前端分页
          this.applyPagination();
          
          // 成功提示
          if (tasks.length > 0) {
            this.$message.success('成功加载 ' + tasks.length + ' 个定时任务');
          } else {
            this.$message.info('暂无符合条件的定时任务');
          }
        } else if (res && res.msg) {
          this.$message.error('获取定时任务失败：' + res.msg);
        } else {
          this.$message.error('获取定时任务失败：网络错误或后端服务未启动');
        }
        this.loading = false;
      }).catch(err => {
        this.$message.error('获取定时任务失败：网络连接异常');
        console.error('API请求失败:', err);
        this.loading = false;
      });
    },
    
    // 前端分页
    applyPagination() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      this.taskData = this.allTasks.slice(startIndex, endIndex);
    },
    
    // 搜索任务
    searchTasks() {
      this.currentPage = 1;
      this.loadTaskData();
    },
    
    // 导出任务记录
    exportTasks() {
      this.$message.info('正在导出任务记录，请稍候...');
      
      // 将当前筛选结果转换为CSV格式
      const csvData = this.convertToCSV(this.allTasks);
      const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = '智能锁定时任务记录_' + this.getFormattedDateTime() + '.csv';
      link.click();
      window.URL.revokeObjectURL(url);
      this.$message.success('任务记录导出成功');
    },
    
    // 转换为CSV格式  
    convertToCSV(data) {
      const header = '任务ID,设备ID,任务详情,执行时间,重复周期,任务状态,创建时间,通道号\n';
      const rows = data.map(task => {
        const taskStatus = this.getTaskStatus(task.taskStatus);
        const executeTime = this.formatTime(task.hour, task.minute);
        const repeatDays = this.formatDays(task.countDay).join('、');
        const createdTime = this.formatDate(task.createdTime);
        return [
          task.taskId || '',
          task.lockId || '',
          task.taskDetails || '定时开锁任务',
          executeTime,
          repeatDays,
          taskStatus,
          createdTime,
          task.remarks || ''
        ].join(',');
      });
      return header + rows.join('\n');
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.statusFilter = '';
      this.dateRange = null;
      this.currentPage = 1;
      this.$message.info('已重置搜索条件');
      this.loadTaskData();
    },
    
    // 查看详情
    viewDetails(row) {
      this.selectedTask = row;
      this.dialogVisible = true;
    },
    
    // 分页相关
    handleCurrentChange(page) {
      this.currentPage = page;
      this.applyPagination();
    },
    
    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.applyPagination();
    },
    
    // 格式化时间显示
    formatTime(hour, minute) {
      const h = String(hour || 0).padStart(2, '0');
      const m = String(minute || 0).padStart(2, '0');
      return `${h}:${m}`;
    },
    
    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '未知';
      
      if (typeof timestamp === 'string' && timestamp.includes('-')) {
        return timestamp;
      }
      
      if (typeof timestamp === 'number') {
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hour = String(date.getHours()).padStart(2, '0');
        const minute = String(date.getMinutes()).padStart(2, '0');
        const second = String(date.getSeconds()).padStart(2, '0');
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
      }
      
      return timestamp.toString();
    },
    
    // 获取格式化的当前日期时间（用于文件名）
    getFormattedDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hour = String(now.getHours()).padStart(2, '0');
      const minute = String(now.getMinutes()).padStart(2, '0');
      const second = String(now.getSeconds()).padStart(2, '0');
      return year + month + day + hour + minute + second;
    },
    
    // 格式化重复天数显示
    formatDays(countDay) {
      if (!countDay) return [];
      
      try {
        let days = [];
        
        // 处理JSON格式，如 "[0]", "[0,1,2,3,4,5,6]"
        if (typeof countDay === 'string' && countDay.includes('[')) {
          // 解析 JSON 格式
          days = JSON.parse(countDay);
        } else if (typeof countDay === 'string') {
          // 处理逗号分隔格式 "1,2,3,4,5"
          days = countDay.split(',').map(day => parseInt(day.trim())).filter(day => !isNaN(day));
        } else if (Array.isArray(countDay)) {
          // 如果已经是数组
          days = countDay;
        }
        
        // 确保都是数字
        days = days.map(day => parseInt(day)).filter(day => !isNaN(day));
        
        const dayNames = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
        return days.map(day => dayNames[day] || `第${day}天`);
      } catch (e) {
        console.warn('解析 countDay 失败:', countDay, e);
        return [];
      }
    },
    
    // 获取任务状态
    getTaskStatus(taskStatus) {
      switch(taskStatus) {
        case 0:
          return '待执行';
        case 1:
          return '执行中';
        case 2:
          return '已完成';
        case 3:
          return '已取消';
        default:
          return '未知状态';
      }
    },
    
    // 获取任务状态标签类型
    getTaskStatusType(taskStatus) {
      switch(taskStatus) {
        case 0:
          return 'info';       // 待执行 - 蓝色
        case 1:
          return 'success';    // 执行中 - 绿色
        case 2:
          return 'primary';    // 已完成 - 主色调
        case 3:
          return 'danger';     // 已取消 - 红色
        default:
          return '';           // 默认
      }
    },
    
    // 取消任务
    cancelTask(task) {
      this.$confirm(
        `确定要取消任务"${task.taskDetails || '定时开锁任务'}"吗？取消后该任务将不再执行。`, 
        '取消任务确认', 
        {
          confirmButtonText: '确定取消',
          cancelButtonText: '保留任务',
          type: 'warning',
          center: true
        }
      ).then(() => {
        this.executeCancelTask(task);
      }).catch(() => {
        this.$message.info('已保留任务');
      });
    },
    
    // 执行取消任务
    executeCancelTask(task) {
      task.cancelling = true;
      
      this.$post(TIMER_API.CANCEL_TIMER, {
        taskId: task.taskId,
        lockId: task.lockId,
        taskStatus: 3
      })
      .then(res => {
        if (res && res.code === 200) {
          this.$message.success('任务取消成功！');
          
          // 更新本地状态
          task.taskStatus = 3;
          
          // 刷新数据
          setTimeout(() => {
            this.loadTaskData();
          }, 1000);
        } else {
          this.$message.error(res.msg || '取消任务失败');
        }
      })
      .catch(error => {
        console.error('取消任务失败:', error);
        this.$message.error('取消任务失败: ' + (error.message || '网络异常'));
      })
      .finally(() => {
        task.cancelling = false;
      });
    },
    
    // 刷新数据
    refreshData() {
      this.$message.info('正在刷新数据...');
      this.loadTaskData();
    },
    
    // ========== 批量操作相关方法 ==========
    
    // 处理选择变化
    handleSelectionChange(selection) {
      this.selectedTasks = selection;
    },
    
    // 检查是否可选择（只有执行中的任务才能被选择进行批量操作）
    checkSelectable(row) {
      return row.taskStatus === 1; // 只有执行中的任务才能选择
    },
    
    // 清空选择
    clearSelection() {
      this.$refs.taskTable.clearSelection();
      this.selectedTasks = [];
      this.$message.info('已清空选择');
    },
    
    // 批量取消任务
    batchCancelTasks() {
      if (this.selectedTasks.length === 0) {
        this.$message.warning('请先选择要取消的任务');
        return;
      }
      
      // 确认对话框
      this.$confirm(
        `确定要批量取消选中的 ${this.selectedTasks.length} 个任务吗？取消后这些任务将不再执行。`, 
        '批量取消任务确认', 
        {
          confirmButtonText: '确定取消',
          cancelButtonText: '保留任务',
          type: 'warning',
          center: true
        }
      ).then(() => {
        this.executeBatchCancel();
      }).catch(() => {
        this.$message.info('已保留所有任务');
      });
    },
    
    // 执行批量取消
    async executeBatchCancel() {
      this.batchCancelling = true;
      const totalTasks = this.selectedTasks.length;
      let successCount = 0;
      let failCount = 0;
      
      try {
        // 显示进度提示
        this.$message.info(`正在批量取消任务，共 ${totalTasks} 个...`);
        
        // 并发执行取消任务，但限制并发数量避免服务器压力过大
        const batchSize = 3; // 每次并发3个请求
        for (let i = 0; i < this.selectedTasks.length; i += batchSize) {
          const batch = this.selectedTasks.slice(i, i + batchSize);
          const promises = batch.map(task => this.cancelSingleTaskInBatch(task));
          
          // 使用兼容性更好的方法替代 Promise.allSettled
          const results = await this.promiseAllSettledPolyfill(promises);
          results.forEach(result => {
            if (result.status === 'fulfilled' && result.value) {
              successCount++;
            } else {
              failCount++;
            }
          });
          
          // 批次间稍作延迟
          if (i + batchSize < this.selectedTasks.length) {
            await new Promise(resolve => setTimeout(resolve, 500));
          }
        }
        
        // 显示结果
        if (successCount === totalTasks) {
          this.$message.success(`批量取消成功！共处理 ${totalTasks} 个任务`);
        } else if (successCount > 0) {
          this.$message.warning(`部分取消成功：成功 ${successCount} 个，失败 ${failCount} 个`);
        } else {
          this.$message.error(`批量取消失败！共 ${failCount} 个任务取消失败`);
        }
        
        // 清空选择并刷新数据
        this.clearSelection();
        setTimeout(() => {
          this.loadTaskData();
        }, 1000);
        
      } catch (error) {
        console.error('批量取消任务失败:', error);
        this.$message.error('批量取消任务时发生错误: ' + (error.message || '网络异常'));
      } finally {
        this.batchCancelling = false;
      }
    },
    
    // Promise.allSettled 兼容性 polyfill
    promiseAllSettledPolyfill(promises) {
      return Promise.all(
        promises.map(promise => 
          Promise.resolve(promise)
            .then(value => ({ status: 'fulfilled', value }))
            .catch(reason => ({ status: 'rejected', reason }))
        )
      );
    },
    
    // 单个任务取消（用于批量操作）
    cancelSingleTaskInBatch(task) {
      return new Promise((resolve) => {
        this.$post(TIMER_API.CANCEL_TIMER, {
          taskId: task.taskId,
          lockId: task.lockId,
          taskStatus: 3
        })
        .then(res => {
          if (res && res.code === 200) {
            // 更新本地状态
            task.taskStatus = 3;
            resolve(true);
          } else {
            console.error(`取消任务 ${task.taskId} 失败:`, res.msg || '未知错误');
            resolve(false);
          }
        })
        .catch(error => {
          console.error(`取消任务 ${task.taskId} 失败:`, error);
          resolve(false);
        });
      });
    },
    
    // 批量导出选中项
    batchExportTasks() {
      if (this.selectedTasks.length === 0) {
        this.$message.warning('请先选择要导出的任务');
        return;
      }
      
      this.$message.info(`正在导出 ${this.selectedTasks.length} 个选中的任务记录...`);
      
      // 导出选中的任务
      const csvData = this.convertToCSV(this.selectedTasks);
      const blob = new Blob([csvData], { type: 'text/csv;charset=utf-8;' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `智能锁定时任务记录_选中项_${this.selectedTasks.length}个_${this.getFormattedDateTime()}.csv`;
      link.click();
      window.URL.revokeObjectURL(url);
      
      this.$message.success(`成功导出 ${this.selectedTasks.length} 个选中任务记录`);
    },
    
    // ========== 任务编辑相关方法 ==========
    
    // 启动任务
    startTask(task) {
      this.isStartMode = true;
      this.editDialogTitle = '启动任务 - ' + (task.taskDetails || '定时开锁任务');
      this.openEditDialog(task);
    },
    
    // 编辑任务
    editTask(task) {
      this.isStartMode = false;
      this.editDialogTitle = '编辑任务 - ' + (task.taskDetails || '定时开锁任务');
      this.openEditDialog(task);
    },
    
    // 打开编辑对话框
    openEditDialog(task) {
      // 填充表单数据
      this.editForm.taskId = task.taskId;
      this.editForm.lockId = task.lockId;
      this.editForm.taskDetails = task.taskDetails || '';
      this.editForm.remarks = task.remarks || '';
      this.editForm.loopCount = task.loopCount || 0;
      
      // 设置执行时间
      const hour = String(task.hour || 0).padStart(2, '0');
      const minute = String(task.minute || 0).padStart(2, '0');
      this.editForm.executeTime = `${hour}:${minute}`;
      this.editForm.hour = task.hour || 0;
      this.editForm.minute = task.minute || 0;
      
      // 解析重复周期
      this.editForm.countDayArray = this.parseCountDayToArray(task.countDay);
      
      this.editDialogVisible = true;
    },
    
    // 解析重复周期字符串为数组
    parseCountDayToArray(countDay) {
      if (!countDay) return [];
      
      try {
        let days = [];
        
        // 处理JSON格式，如 "[0]", "[0,1,2,3,4,5,6]"
        if (typeof countDay === 'string' && countDay.includes('[')) {
          // 解析 JSON 格式
          days = JSON.parse(countDay);
        } else if (typeof countDay === 'string') {
          // 处理逗号分隔格式 "1,2,3,4,5"
          days = countDay.split(',').map(day => parseInt(day.trim())).filter(day => !isNaN(day));
        } else if (Array.isArray(countDay)) {
          // 如果已经是数组
          days = countDay;
        }
        
        // 确保都是数字
        return days.map(day => parseInt(day)).filter(day => !isNaN(day));
      } catch (e) {
        console.warn('解析重复周期失败:', countDay, e);
        return [];
      }
    },
    
    // 数组转换为重复周期字符串
    parseArrayToCountDay(dayArray) {
      if (!dayArray || dayArray.length === 0) return '';
      return dayArray.join(',');
    },
    
    
    // 重置编辑表单
    resetEditForm() {
      if (this.$refs.editForm) {
        this.$refs.editForm.resetFields();
      }
      
      this.editForm = {
        taskId: '',
        lockId: '',
        taskDetails: '',
        remarks: '',
        executeTime: '',
        countDayArray: [],
        loopCount: 0,
        hour: 0,
        minute: 0
      };
      
      this.editSubmitting = false;
      this.isStartMode = false;
    },
    
    // 处理编辑确认
    handleEditConfirm() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.submitEditForm();
        } else {
          this.$message.error('请检查表单填写是否正确');
          return false;
        }
      });
    },
    
    // 提交编辑表单
    async submitEditForm() {
      this.editSubmitting = true;
      
      try {
        // 解析执行时间
        if (this.editForm.executeTime) {
          const [hour, minute] = this.editForm.executeTime.split(':');
          this.editForm.hour = parseInt(hour);
          this.editForm.minute = parseInt(minute);
        }
        
        if (this.isStartMode) {
          // 启动任务模式 - 先调用 updateTimer 接口，再调用 updateTimerStatus 接口
          
          // 第一步：调用 updateTimer 接口更新任务信息
          const updateData = {
            taskId: this.editForm.taskId,
            lockId: this.editForm.lockId,
            taskDetails: this.editForm.taskDetails,
            remarks: this.editForm.remarks,
            hour: this.editForm.hour,
            minute: this.editForm.minute,
            loopCount: this.editForm.loopCount,
            countDay: this.editForm.countDayArray
          };
          
          const updateRes = await this.$post(TIMER_API.UPDATE_TIMER, updateData);
          
          if (updateRes && updateRes.code === 200) {
            this.$message.success('任务信息更新成功！');
            
            // 更新本地数据
            const taskIndex = this.allTasks.findIndex(task => task.taskId === updateData.taskId);
            if (taskIndex !== -1) {
              this.allTasks[taskIndex] = { 
                ...this.allTasks[taskIndex], 
                ...updateData,
                countDay: this.parseArrayToCountDay(updateData.countDay)
              };
            }
            
            // 第二步：调用 updateTimerStatus 接口启动任务
            const statusData = {
              taskId: this.editForm.taskId,
              lockId: this.editForm.lockId,
              taskStatus: 1 // 设置为执行中
            };
            
            const statusRes = await this.$post(TIMER_API.UPDATE_TIMER_STATUS, statusData);
            
            if (statusRes && statusRes.code === 200) {
              this.$message.success('任务启动成功！');
              
              // 更新本地数据状态
              if (taskIndex !== -1) {
                this.allTasks[taskIndex].taskStatus = 1;
              }
            } else {
              throw new Error((statusRes && statusRes.msg) || '启动任务失败');
            }
          } else {
            throw new Error((updateRes && updateRes.msg) || '更新任务信息失败');
          }
        } else {
          // 编辑任务模式 - 调用 updateTimer 接口
          const updateData = {
            taskId: this.editForm.taskId,
            lockId: this.editForm.lockId,
            taskDetails: this.editForm.taskDetails,
            remarks: this.editForm.remarks,
            hour: this.editForm.hour,
            minute: this.editForm.minute,
            loopCount: this.editForm.loopCount,
            countDay: this.editForm.countDayArray
          };
          
          const updateRes = await this.$post(TIMER_API.UPDATE_TIMER, updateData);
          
          if (updateRes && updateRes.code === 200) {
            this.$message.success('任务信息修改成功！');
            
            // 更新本地数据
            const taskIndex = this.allTasks.findIndex(task => task.taskId === updateData.taskId);
            if (taskIndex !== -1) {
              this.allTasks[taskIndex] = { 
                ...this.allTasks[taskIndex], 
                ...updateData,
                countDay: this.parseArrayToCountDay(updateData.countDay)
              };
            }
          } else {
            throw new Error((updateRes && updateRes.msg) || '修改任务失败');
          }
        }
        
        // 刷新表格显示
        this.applyPagination();
        
        // 关闭对话框
        this.editDialogVisible = false;
        
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败: ' + (error.message || '未知错误'));
      } finally {
        this.editSubmitting = false;
      }
    }
  }
}
</script>

<style scoped>
.smartlock-timer-container {
  padding: 20px;
  background-color: #fff;
  height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
  position: relative;
  /* 确保滚动平滑 */
  scroll-behavior: smooth;
  /* 防止内容溢出到父容器 */
  contain: layout style paint;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header-left h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 500;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.header-right {
  display: flex;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 15px 0;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

/* 详情对话框标题样式 */
.el-dialog h4 {
  margin: 15px 0 10px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
  margin-top: 10px;
}

.el-table .cell {
  padding: 0 8px;
}

.el-table th {
  background-color: #fafafa;
}

.el-table--border td, .el-table--border th {
  border-right: 1px solid #ebeef5;
}

/* 标签样式优化 */
.el-tag {
  border-radius: 4px;
}

/* 描述列表样式优化 */
.el-descriptions {
  margin-bottom: 0;
}

.el-descriptions__label {
  font-weight: 600;
  color: #606266;
}

.el-descriptions__content {
  color: #303133;
}

/* 表单项间距 */
.el-form--inline .el-form-item {
  margin-right: 15px;
  margin-bottom: 10px;
}

/* 按钮组样式 */
.el-form-item:last-child {
  margin-right: 0;
}

/* 加载状态优化 */
.el-loading-mask {
  border-radius: 8px;
}

/* 响应式设计 */
@media screen and (max-width: 1200px) {
  .el-table {
    font-size: 13px;
  }
  
  .el-table .cell {
    padding: 0 6px;
  }
}

@media screen and (max-width: 768px) {
  .smartlock-timer-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
    text-align: center;
  }
  
  .header-left h2 {
    border-bottom: none;
    padding-bottom: 0;
  }
  
  .header-right {
    justify-content: center;
  }
  
  .search-form {
    padding: 15px;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
    margin-right: 0;
  }
  
  .search-form .el-input,
  .search-form .el-select,
  .search-form .el-date-picker {
    width: 100% !important;
  }
  
  .el-table {
    font-size: 12px;
  }
  
  .pagination-wrapper {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .el-descriptions {
    font-size: 12px;
  }
}

/* 自定义滚动条样式 */
.smartlock-timer-container::-webkit-scrollbar {
  width: 8px;
}

.smartlock-timer-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
  margin: 4px;
}

.smartlock-timer-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
  transition: background 0.3s ease;
}

.smartlock-timer-container::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

.smartlock-timer-container::-webkit-scrollbar-corner {
  background: transparent;
}

/* 批量操作工具栏样式 */
.batch-operation-toolbar {
  margin-bottom: 15px;
  padding: 12px 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.batch-info {
  color: #606266;
  font-size: 14px;
}

.batch-info strong {
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
}

.batch-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.batch-actions .el-button {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.batch-actions .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 选择列样式优化 */
.el-table .el-table__header .el-checkbox {
  transform: scale(1.1);
}

.el-table .el-table__body .el-checkbox {
  transform: scale(1.05);
}

/* 选中行高亮 */
.el-table .el-table__row.current-row {
  background-color: #ecf5ff !important;
}

/* 不可选择行的样式 */
.el-table .el-table__row.disabled-row {
  background-color: #f5f7fa;
  color: #c0c4cc;
}

.el-table .el-table__row.disabled-row .el-checkbox {
  cursor: not-allowed;
}

/* 批量操作按钮特殊样式 */
.batch-actions .el-button--danger {
  background: linear-gradient(135deg, #f56c6c, #f78989);
  border: none;
  color: white;
}

.batch-actions .el-button--danger:hover {
  background: linear-gradient(135deg, #f78989, #fbc4ab);
}

.batch-actions .el-button--success {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  border: none;
  color: white;
}

.batch-actions .el-button--success:hover {
  background: linear-gradient(135deg, #85ce61, #b3e19d);
}

.batch-actions .el-button--info {
  background: linear-gradient(135deg, #909399, #b1b3b8);
  border: none;
  color: white;
}

.batch-actions .el-button--info:hover {
  background: linear-gradient(135deg, #b1b3b8, #c8c9cc);
}

/* 深色模式兼容 */
@media (prefers-color-scheme: dark) {
  .smartlock-timer-container {
    background-color: #1a1a1a;
    color: #fff;
  }
  
  .page-header h2 {
    color: #fff;
    border-color: #409eff;
  }
  
  .search-form {
    background-color: #2d2d2d;
    border-color: #404040;
  }
  
  .batch-operation-toolbar {
    background: linear-gradient(135deg, #2d2d2d 0%, #3a3a3a 100%);
    border-color: #404040;
    color: #fff;
  }
  
  .batch-info {
    color: #b1b3b8;
  }
  
  .batch-info strong {
    color: #67c23a;
  }
}

/* 编辑表单样式 */
.form-section {
  margin-bottom: 25px;
}

.form-section h4 {
  margin: 0 0 15px 0;
  color: #409eff;
  font-size: 16px;
  font-weight: 600;
  border-left: 4px solid #409eff;
  padding-left: 10px;
  background-color: #f0f9ff;
  padding: 8px 0 8px 10px;
  border-radius: 4px;
}

.form-section .el-form-item {
  margin-bottom: 18px;
}

/* 时间选择器样式 */
.el-time-picker {
  width: 100%;
}

/* 多选框组样式 */
.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.el-checkbox-group .el-checkbox {
  margin-right: 0;
}

/* 数字输入框样式 */
.el-input-number {
  width: 200px;
}

/* 表单验证错误样式优化 */
.el-form-item.is-error .el-input__inner,
.el-form-item.is-error .el-textarea__inner {
  border-color: #f56c6c;
}

.el-form-item.is-error .el-form-item__error {
  color: #f56c6c;
  font-size: 12px;
  padding-top: 4px;
}

/* 对话框内容样式 */
.el-dialog__body {
  padding: 20px 20px 10px 20px;
}

.el-dialog__footer {
  padding: 10px 20px 20px 20px;
  text-align: right;
}

/* 操作按钮颜色优化 */
.el-button--text {
  padding: 0;
  font-weight: 500;
}

.el-button--text:hover {
  background-color: transparent;
}

/* 响应式设计优化 */
@media screen and (max-width: 768px) {
  .batch-operation-toolbar {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
    text-align: center;
  }
  
  .batch-actions {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .batch-actions .el-button {
    flex: 1;
    min-width: 80px;
  }
  
  /* 编辑表单移动端优化 */
  .form-section .el-row {
    flex-direction: column;
  }
  
  .form-section .el-col {
    width: 100% !important;
    margin-bottom: 10px;
  }
  
  .el-checkbox-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .el-input-number {
    width: 100%;
  }
  
  .el-dialog {
    width: 95% !important;
    margin: 0 auto !important;
  }
  
  .el-dialog__body {
    padding: 15px 15px 10px 15px;
  }
  
  .form-section h4 {
    font-size: 14px;
    padding: 6px 0 6px 8px;
  }
}
</style>
